package problems.painteddesert;

public abstract class Ant {
	private static final int EMPTY = -1;
	private int _x;
	private int _y;
	private int _current_grain = -1;
	private World _world;

	public Ant() {
	}

	public Ant(World world) {
		_world = world;

	}

	public abstract void step();

	public int getX() {
		return _x;
	}

	public int getY() {
		return _y;
	}

	public int getCarryingColor() {
		int color = _current_grain;

		if (color == 0) {
			color = -1;
		}

		return color;
	}

	public int getColor() {
		int color = _world.getColor(getX(), getY());

		if (color == 0) {
			color = -1;
		}

		return color;
	}

	public int moveNorth() {
		_y += 1;
		if (_y >= _world.getHeight()) {
			_y = 0;
		}

		return getColor();
	}

	public int moveSouth() {
		_y -= 1;
		if (_y < 0) {
			_y = _world.getHeight() - 1;
		}

		return getColor();
	}

	public int moveEast() {
		_x += 1;
		if (_x >= _world.getWidth()) {
			_x = 0;
		}

		return getColor();
	}

	public int moveWest() {
		_x -= 1;
		if (_x < 0) {
			_x = _world.getWidth() - 1;
		}

		return getColor();
	}

	public int moveRandom() {
		switch ((int) (4 * Math.random())) {
		case 0:
			moveNorth();
			break;
		case 1:
			moveSouth();
			break;
		case 2:
			moveEast();
			break;
		case 3:
			moveWest();
			break;
		}

		return getColor();
	}

	public int pickUp() {
		if (getCarryingColor() == EMPTY) {
			_current_grain = getColor();
			_world.setColor(getX(), getY(), World.EMPTY);
		}

		return getColor();
	}

	public int drop() {
		if (getCarryingColor() > EMPTY && getColor() == EMPTY) {
			_world.setColor(getX(), getY(), _current_grain);
			_current_grain = EMPTY;
		}
		return getColor();
	}

	public boolean canDrop() {
		return (getCarryingColor() == EMPTY) && getColor() == EMPTY;
	}

	public void setWorld(World world) {
		_world = world;

		_x = (int) (Math.random() * _world.getWidth());
		_y = (int) (Math.random() * _world.getHeight());
	}

	public void setPos(int[] pos) {
		_x = pos[0];
		_y = pos[1];
	}
}
